<?php

// +----------------------------------------------------------------------
// |  SendCloud邮件发送类
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace yicmf\tools;

class SendCloud
{
    //用户apiUser
    private $apiUser = '';

     //用户apiKey
    private $apiKey = '';

    /***
     * 请求根地址
     */
    private $api = 'http://api.sendcloud.net/apiv2';

    private $fromName = '';
    private $from;

    /**
     *  $send=new  yicmf\SendCloud('yicmf_trigger', 'VzmvowlD7noUE6jP');
     *  $send->mailSendTemplate('9462665@qq.com','YiCmf通知信息','register_info',[]) ;.
     *
     * @param unknown $apiUser
     * @param unknown $apiKey
     * @param string  $fromName
     * @param unknown $from
     * @date		2016年4月5日 下午1:45:11
     *
     * @author		@微尘 <yicmf@qq.com>
     *
     * @version	v1.0.0
     */
    public function __construct($apiUser, $apiKey, $fromName = '', $from = null)
    {
        $this->apiKey = $apiKey;
        $this->apiUser = $apiUser;
        $this->fromName = 'YiCmf邮件中心';
        $this->from = $from ?: 'info@yicmf.cn';
    }

    /**
     * 发送普通邮件.
     *
     * @author		@微尘 <yicmf@qq.com>
     *
     * @version	v1.0.0
     */
    public function mailSend($to, $subject, $html)
    {
        $param = [
            'to'      => $to, // 收件人地址, 用正确邮件地址替代, 多个地址用';'分隔
            'subject' => $subject, // 'Sendcloud php webapi common example',
            'html'    => $html, //'亲爱的%name%: 您好!您已经成功注册新闻链接100%，感谢您的使用。'
        ];

        return $this->api('mail/send', $param);
    }

    /**
     * 发送模版消息.
     *
     * @author		@微尘 <yicmf@qq.com>
     *
     * @version	v1.0.0
     */
    public function mailSendTemplate($to, $subject, $templateInvokeName, $params)
    {
        $param = [
            'to'                 => $to, // 收件人地址, 用正确邮件地址替代, 多个地址用';'分隔
            'xsmtpapi'           => $this->getXsmtpapi($to, $params),
            'subject'            => $subject,
            'templateInvokeName' => $templateInvokeName,
        ];

        return $this->api('mail/sendtemplate', $param);
    }

    protected function getXsmtpapi($to, $params)
    {
        $data['to'] = [$to];
        $data['sub'] = ['%name%'=>['用户名'], '%web_site%'=>['这是网站名字']];

        return json_encode($data);
    }

    /**
     * @param string $name   API名称
     * @param string $param  GET请求参数
     * @param string $method 请求方式
     *
     * @return array api返回结果
     */
    protected function api($name, $param = '', $method = 'POST')
    {
        $params = [
            'apiUser'  => $this->apiUser, // 使用api_user和api_key进行验证
            'apiKey'   => $this->apiKey,
            'from'     => $this->from, // 'info@yicmf.cn', # 发信人，用正确邮件地址替代
            'fromName' => $this->fromName,
            ];

        if (!empty($param) && is_array($param)) {
            $params = array_merge($params, $param);
        }
        $url = "{$this->api}/{$name}";

        return json_decode(self::http($url, $params, $method), true);
    }

    /**
     * 发送HTTP请求方法，目前只支持CURL发送请求
     *
     * @param string $url    请求URL
     * @param array  $param  GET参数数组
     * @param array  $data   POST的数据，GET请求时该参数无效
     * @param string $method 请求方法GET/POST
     *
     * @return array 响应数据
     */
    protected static function http($url, $data = '', $method = 'GET')
    {
        $opts = [
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ];

        /* 根据请求类型设置特定参数 */
        $opts[CURLOPT_URL] = $url;

        if (strtoupper($method) == 'POST') {
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $data;

            if (is_string($data)) { //发送JSON数据
                $opts[CURLOPT_HTTPHEADER] = [
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: '.strlen($data),
                ];
            }
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        //发生错误，抛出异常
        if ($error) {
            throw new \Exception('请求发生错误：'.$error);
        }

        return  $data;
    }
}
